import mainConfig from "@/pages_nbst/utils/config.js"
import tools from "@/pages_nbst/utils/tools.js"

const requestConfig = {
	baseUrl: mainConfig.baseUrl,
	header: {},
	reqCheckToken: true,
	loading: true,
	timeout: 5000,
	method: 'get',
	url: '',
	data: {},
	params: {}
}

export function request(config) {
	return new Promise((resolve, reject) => {
		config = {
			...requestConfig,
			...config
		}
		console.log(config)
		if (config?.loading !== false) {
			uni.showLoading({
				title: '易公加载中'
			})
		}
		// before
		if (config?.reqCheckToken !== false) {
			if (!tools.getToken()) {
				uni.showToast({
					title: "用户失效",
					icon: "error"
				})
				tools.setToken()
				uni.reLaunch({
					url: mainConfig.indexUrl
				})
			}
		}
		// config
		config.url = config.baseUrl + config.url
		config.method = config.method.toUpperCase()
		config.header[mainConfig.headerTokenKey] = tools.getToken()
		if (config.method === 'POST') {
			config.header['content-type'] = 'application/json'
		}
		if (config.method === 'GET') {
			config.data = config.params
		}
		uni.request(config).then((res) => {
			if (res.statusCode === 200) {
				const resp = res.data
				console.log(resp)
				if (resp.code === 20000) {
					return resolve(resp.data)
				} else if (resp.code === 20504) {
					uni.showToast({
						icon: "error",
						title: resp.msg || "用户失效"
					})
					tools.setToken()
					uni.reLaunch({
						url: mainConfig.indexUrl
					})
					return reject(resp)
				} else {
					uni.showToast({
						icon: "error",
						title: resp.msg || "未知错误",
					})
					return reject(resp)
				}
			} else {
				console.log(res);
				uni.showToast({
					icon: "error",
					title: res.data || res.errMsg || "请联系管理",
				})
				return reject(res)
			}
		}).catch((err) => {
			console.error(err);
			reject(err)
		}).finally(() => {
			if (config?.loading !== false) {
				uni.hideLoading()
			}
		})
	})
}